package cn.com.se.sharepictrue.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.adapter.AbstractRecyclerAdapter;
import cn.com.se.sharepictrue.adapter.CommentAdapter;
import cn.com.se.sharepictrue.adapter.ShareImgAdapter;
import cn.com.se.sharepictrue.adapter.ShareListAdapter;
import cn.com.se.sharepictrue.application.Data;
import cn.com.se.sharepictrue.bean.Comment;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.bean.UserInfoBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.ImageLoader;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.quickadapter.BaseAdapterHelper;
import cn.com.se.sharepictrue.utils.StringUtils;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cn.com.se.sharepictrue.widget.AdapterGridLayout;
import cn.com.se.sharepictrue.widget.AdapterLinearLayout;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 分享图片详情界面
 * Created by KIDNG on 2015/11/3.
 */
public class ShareDetailActivity extends ActionBarActivity implements ShareListAdapter.ShareItemStatusListener {
    private static final int REQUEST_CODE_COMMENT = 1;
    @Bind(R.id.tb_share_detail_toolbar)
    Toolbar mTbShareDetailToolbar;
    @Bind(R.id.tv_share_detail_collection)
    TextView mTvCollection;
    @Bind(R.id.tv_share_detail_comment)
    TextView mTvComment;
    @Bind(R.id.tv_share_detail_praise)
    TextView mTvPraise;
    @Bind(R.id.iv_item_share_avatar)
    CircleImageView mAvatar;
    @Bind(R.id.tv_item_share_name)
    TextView mTvName;
    @Bind(R.id.tv_item_share_time)
    TextView mTvTime;
    @Bind(R.id.iv_item_share_collection)
    ImageView mIvConcern;
    @Bind(R.id.tv_item_share_signature)
    TextView mTvSignature;
    @Bind(R.id.tv_item_share_content)
    TextView mTvContent;
    @Bind(R.id.gv_item_share_many_img)
    AdapterGridLayout mGvImgs;
    @Bind(R.id.ll_share_list_bottom)
    LinearLayout mLlShareListBottom;
    @Bind(R.id.all_share_detail_comments)
    AdapterLinearLayout mAllComments;

    private HomeShareBean detail;
    private int whatPosition;
    private List<Comment> mCommentList;
    private String mUserID;
    private CommentAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_detail);
        ButterKnife.bind(this);
        getUserInfo();
        initToolbar();
        initHeader();
        initBottomLayout();
        initComment();
    }

    private void getUserInfo() {
        UserInfoBean userInfo = ((Data) getApplicationContext()).getUserInfo();
        if (userInfo != null && userInfo.isHaveData()) {
            mUserID = userInfo.getUserID();
        }
    }

    private void initComment() {
        ShareApi.getShareComment(this, detail.getShareId(), new CallBack<NetworkResponse<List<Comment>>>(this) {
            @Override
            public void onFail() {
                ToastUtils.show(ShareDetailActivity.this, "网络访问失败咯");
            }

            @Override
            public void onResponse(NetworkResponse<List<Comment>> response) {
                if (!response.isStatus()) {
                    ToastUtils.show(ShareDetailActivity.this, response.getError());
                } else {
                    mCommentList = response.getData();
                    setupComment();
                }
            }
        });
    }

    private void setupComment() {
        if (mCommentList != null && mCommentList.size() > 0) {
            mAdapter = new CommentAdapter(this, mCommentList);
            mAdapter.setOnItemClickListener(new AbstractRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(ViewGroup parent, View view, int position, long id) {
                    if (!StringUtils.isEmpty(mUserID)) {
                        Intent intent = new Intent(ShareDetailActivity.this, SendMessageActivity.class);
                        Comment comment = mAdapter.getItem(position);
                        intent.putExtra(SendMessageActivity.BUNDLE_KEY_BEAN, comment);
                        intent.putExtra(SendMessageActivity.BUNDLE_KEY_TYPE, SendMessageActivity.TYPE_SEND_REPLY);
                        startActivityForResult(intent, REQUEST_CODE_COMMENT);
                    }
                }
            });
            mAllComments.setAdapter(mAdapter);
        }
    }


    private void initHeader() {
        Intent intent = getIntent();
        Bundle bundle = null;
        if (intent != null) {
            bundle = intent.getBundleExtra("item");
            whatPosition = intent.getIntExtra("position", -1);
        }
        if (bundle != null)
            detail = (HomeShareBean) bundle.getSerializable("key");
        if (detail != null) {
            if (!StringUtils.isEmpty(detail.getUserName()))
                mTbShareDetailToolbar.setTitle(detail.getUserName());
            mTvName.setText(detail.getUserName());
            mTvSignature.setText(detail.getSignature());
            mTvTime.setText(detail.getAddTime());
            mTvContent.setText(detail.getShareContent());
            mLlShareListBottom.setVisibility(View.GONE);
            //==================头像=================
            initAvatarView();

            //============关注用户===================
            setConcernViewByStatus();

            //==============分享图片列表====================
            List<String> imgUrls = detail.getImgs();
            if (imgUrls != null && imgUrls.size() > 0) {
                mGvImgs.setVisibility(View.VISIBLE);
                ShareImgAdapter adapter = new ShareImgAdapter(this, imgUrls);
                mGvImgs.setAdapter(adapter);
            } else {
                mGvImgs.setVisibility(View.GONE);
            }



        } else {
            ToastUtils.show(this, "没有数据！！！");
        }

    }

    private void initBottomLayout() {
        //===========收藏===========
        setCollectionViewByStatus();

        //===========点赞===========
        setPraiseViewByStatus();

        //===========评论============
        initCommentView();
    }

    private void initAvatarView() {
        if (detail.getAvatar() != null)
            ImageLoader.getInstance(this).load(mAvatar, detail.getAvatar());
        mAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShareDetailActivity.this, PersonalHomepageActivity.class);
                Bundle bundle = new Bundle();
                //bundle.putSerializable(PersonalHomepageActivity.HOMEPAGE_SHAREINFO, item);
                bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERID, detail.getUserId());
                bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERNAME, detail.getUserName());
                bundle.putString(PersonalHomepageActivity.HOMEPGE_USERPIC, detail.getAvatar());
                if (((Data) (ShareDetailActivity.this.getApplicationContext())).isLogin() && detail.getUserId().contentEquals(((Data) (ShareDetailActivity.this.getApplicationContext())).getUserInfo().getUserID()))
                    bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_ME);
                else
                    bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_OTHER);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    private void initCommentView() {
        if (detail != null) {
            mTvComment.setText(detail.getCommentNum() + "");
            mTvComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    commentClick(null, detail);
                }
            });
        }
    }

    private void setPraiseViewByStatus() {
        mTvPraise.setText(detail.getPraiseNum() + "");
        if (!mTvPraise.hasOnClickListeners()) {
            mTvPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    praiseClick(null, detail);
                }
            });
        }
    }

    private void setConcernViewByStatus() {
        if (detail.getConcernUserId() != null && !detail.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
            mIvConcern.setColorFilter(getResources().getColor(R.color.color_item_share_collection),
                    PorterDuff.Mode.SRC_ATOP);//position error
        else
            mIvConcern.clearColorFilter();
        if (!mIvConcern.hasOnClickListeners()) {
            mIvConcern.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    concernClick(null, detail);
                }
            });
        }
    }

    private void setCollectionViewByStatus() {
        if (detail.getFavoriteStatus() != null) {
            if (detail.getFavoriteStatus().equals(HomeShareBean.HOME_SHARE_IS_FAVORITE))
                mTvCollection.setText(getResources().getString(R.string.item_share_collection_selected));
            else
                mTvCollection.setText(getResources().getString(R.string.item_share_collection_normal));
        } else {
            mTvCollection.setText(getResources().getString(R.string.item_share_collection_normal));
        }
        if (!mTvCollection.hasOnClickListeners()) {
            mTvCollection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    collectionClick(null, detail);
                }
            });
        }
    }

    private void initToolbar() {
        setSupportActionBar(mTbShareDetailToolbar);
        mTbShareDetailToolbar.setTitleTextColor(Color.WHITE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("key", detail);
                intent.putExtra("item", bundle);
                intent.putExtra("position", whatPosition);
                setResult(RESULT_OK, intent);
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("key", detail);
            intent.putExtra("item", bundle);
            intent.putExtra("position", whatPosition);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    public void avatarClick(BaseAdapterHelper helper, HomeShareBean item) {

    }

    @Override
    public void concernClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String concernId = item.getConcernUserId();
        if (concernId == null) ToastUtils.show(ShareDetailActivity.this, "请登录");
        else
            ShareApi.concern(ShareDetailActivity.this, item.getUserId(),
                    concernId.equals(HomeShareBean.HOME_SHARE_NO_CONCERN),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(ShareDetailActivity.this, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(ShareDetailActivity.this, response.getError());
                            else {
                                if (item.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
                                    item.setConcernUserId(item.getUserId());
                                else
                                    item.setConcernUserId(HomeShareBean.HOME_SHARE_NO_CONCERN);
                                setConcernViewByStatus();
                            }

                        }
                    });

    }

    @Override
    public void praiseClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String likeIt = item.getPraiseStatus();
        if (likeIt == null) ToastUtils.show(ShareDetailActivity.this, "请登录");
        else if (likeIt.equals(HomeShareBean.HOME_SHARE_NO_PRAISE)) {
            ShareApi.praise(ShareDetailActivity.this, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(ShareDetailActivity.this, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(ShareDetailActivity.this, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_IS_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() + 1);
                        setPraiseViewByStatus();
                    }
                }
            });
        } else if (likeIt.equals(HomeShareBean.HOME_SHARE_IS_PRAISE)) {
            ShareApi.praise(ShareDetailActivity.this, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(ShareDetailActivity.this, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(ShareDetailActivity.this, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_NO_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() - 1);
                        setPraiseViewByStatus();
                    }
                }
            });
        }
    }

    @Override
    public void collectionClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String favorite = item.getFavoriteStatus();
        if (favorite == null) ToastUtils.show(ShareDetailActivity.this, "请登录");
        else if (favorite.equals(HomeShareBean.HOME_SHARE_NO_FAVORITE)) {
            ShareApi.favorite(ShareDetailActivity.this, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(ShareDetailActivity.this, "收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(ShareDetailActivity.this, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_IS_FAVORITE);
                        setCollectionViewByStatus();
                    }

                }
            });
        } else {
            ShareApi.favorite(ShareDetailActivity.this, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(ShareDetailActivity.this, "取消收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(ShareDetailActivity.this, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_NO_FAVORITE);
                        setCollectionViewByStatus();
                    }
                }
            });
        }
    }

    @Override
    public void commentClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(this, SendMessageActivity.class);
        Comment comment = new Comment();
        comment.setShareID(detail.getShareId());
        intent.putExtra(SendMessageActivity.BUNDLE_KEY_BEAN, comment);
        intent.putExtra(SendMessageActivity.BUNDLE_KEY_TYPE, SendMessageActivity.TYPE_SEND_NEW);
        startActivityForResult(intent, REQUEST_CODE_COMMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_COMMENT && resultCode == Activity.RESULT_OK) {
            initComment();
            detail.setCommentNum(detail.getCommentNum()+1);
            initBottomLayout();
        }
    }
}
